//
//  DecimalTopic.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/8/4.
//

import UIKit

class DecimalTopic: BaseTopic {

    var value: Float = 0.0
    /// 分子
    var numerator: Float = 0
    /// 分母
    var denominator: Float = 1
    
    /// 输入的分子
    var inputNumerator: Float = 0
    /// 输入的分母
    var inputDenominator: Float = 1
    
    init(value: Float, numerator: Float, denominator: Float) {
        self.value = value
        self.numerator = numerator
        self.denominator = denominator
    }
    
    override func setInputAnswer(answer: String?, numerator: Float = 0.0, denominator: Float = 1) {
        self.inputNumerator = numerator
        self.inputDenominator = denominator
    }
    
    override func getTopicDesc() -> String {
        return "\(getValueStr())\\% = \\frac{?}{?}"
    }
    
    override func answerIsCorrect() -> Bool {
        return numerator == inputNumerator && denominator == inputDenominator
    }
    
    override func getResultDesc() -> NSMutableAttributedString {
        var sym = "√"
        var color = UIColor.black
        if !answerIsCorrect() {
            sym = "×"
            color = .red
        }
        
        let desc = "\(getValueStr())% = \(Int(numerator)) / \(Int(denominator)) = (\(Int(inputNumerator)) / \(Int(inputDenominator))) \(sym)"
        
        let attri = NSMutableAttributedString(string: desc)
        let tmpRange = NSRange(location: desc.count - 1, length: 1)
        
        attri.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: tmpRange)
        return attri
    }
    
    private func getValueStr() -> String {
        return String(format: "%.1f", value * 100)
    }
}
